package com.shawn.springboot.integeration.netty.codec;

import com.shawn.springboot.integeration.netty.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangjian
 * @title: RpcEncoder
 * @projectName 12-springboot学习
 * @description: 编码器
 * @date 2021/4/2713:11
 */
@Slf4j
public class RpcEncoder extends MessageToByteEncoder {
    /**使用泛型表示待序列化的实体**/
    private final Class<?> genericClass;
    public RpcEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext chc, Object in, ByteBuf out) {
        /** 发送对象满足的情况下,将其序列化成字节数据后发送出去 **/
        if(genericClass.isInstance(in)) {
            byte[] data = SerializationUtil.serialize(in);
            out.writeInt(data.length);
            out.writeBytes(data);
        }
    }
}
